<!--  -->
<template>
  <div class="maxbg">
    <transition name="fade">
      <div class="pageBody g-bg">
        <!-- <div class="dt-top">
          <div class="logo"></div>
          <div class="down-btn" @click="linkCourse">下载APP</div>
        </div> -->
        <div class="pay-main morphology" style="top: 0">
          <div class="pay-card pay-card2">
            <div class="cd-infor">
              <div class="cd-img">
                <img :src="isCover(courseData.cover)" />
              </div>
              <div class="cd-tl">
                <span class="user-accessMode">
                  <template v-if="courseData.accessMode == 1">
                    限时免费
                  </template>
                  <template
                    v-else-if="
                      courseData.accessMode == 2 && courseData.specialOffer == 1
                    "
                  >
                    VIP折扣
                  </template>
                  <template v-else-if="courseData.accessMode == 4">
                    VIP免费
                  </template>
                </span>
                <span class="user-title">{{ courseData.commodityName }}</span>
              </div>
              <div class="cd-tx"></div>
              <template v-if="courseData.accessMode == 1">
                <!-- <div class="cd-money">免费</div> -->
                <span class="cd-money cd-underLine"
                  >{{ courseData?.price / 1000 }} 芝士</span
                >
              </template>
              <template v-else-if="courseData.accessMode == 2">
                <div class="cd-money">{{ courseData.price / 1000 }}芝士</div>
                <div class="cd-time" v-if="courseData.expiryDateText">
                  有效期：{{ courseData.expiryDateText }}
                </div>
              </template>
              <template v-else>
                <div class="cd-money">VIP限免</div>
              </template>
            </div>

            <div class="price-countdown-div" v-if="courseData.accessMode == 1">
              限时免费
              <div class="price-countdown">
                距结束：仅剩
                <div>{{ countdowm.day }}</div>
                天
                <div>{{ countdowm.hour }}</div>
                时
                <div>{{ countdowm.minute }}</div>
                分
                <div>{{ countdowm.second }}</div>
                秒
              </div>
            </div>
          </div>
          <div class="q-chapter">
            <div class="q-tl">
              <div class="q-name">介绍</div>
            </div>
            <div class="introduce">
              <div class="introduce-tx" v-html="courseData.introduce"></div>
            </div>
          </div>
        </div>

        <div class="vip-box" v-if="!isUserInfoComplete && loginState">
          <div class="vip-inf-img"></div>
          <div class="vip-tl">赠送7天会员，享88折优惠！</div>
          <div class="vip-btn" @click="gotoInforPage">立即完善</div>
        </div>
        <div
          class="vip-box"
          v-if="courseData.accessAuth !== 1 && loginState && isUserInfoComplete"
        >
          <div class="vip-img"></div>
          <div class="vip-tl" v-if="isVip">会员到期时间{{ time }}</div>
          <div class="vip-tl" v-else>VIP会员享受85折优惠！</div>
          <div class="vip-btn" v-if="isVip" @click="gotoPay">会员续费</div>
          <div class="vip-btn" v-else @click="gotoPay">开通会员</div>
        </div>
        <div class="dt-foot" v-if="!loginState">
          <div class="ft-tip">
            <div class="tip-tx">请先下载APP再打开课程，体验会更好</div>
          </div>
          <div class="ft-btn" @click="payCrouse(courseData.specificationId)">
            立即购买
          </div>
        </div>
        <div class="dt-foot-service order-bt-gp" v-else>
          <div class="service" id="service">客服</div>
          <template
            v-if="courseData.accessAuth !== 1 && courseData.accessMode != 1"
          >
            <!-- 付费的 -->
            <div
              class="login-btn"
              v-if="courseData.accessMode === 2"
              @click="payCrouse(courseData.specificationId)"
            >
              <span v-if="courseData.specialOffer"
                >折扣价{{ courseData?.discountPrice / 1000 }}芝士&nbsp;</span
              >立即购买
            </div>
            <!-- vip限免 是否可单独购买 -->
            <!-- 是vip 显示参与学习  -->
            <div
              v-else-if="courseData.accessMode === 4 && isVip"
              class="login-btn"
              @click="isApp = true"
            >
              参与学习
            </div>
            <!-- 不是vip -->
            <!-- 可购买 显示立即购买 -->
            <div
              class="login-btn"
              v-if="
                !isVip &&
                courseData.accessMode === 4 &&
                courseData.specialOffer == 2
              "
            >
              <span>{{ courseData?.price / 1000 }}芝士&nbsp;</span>立即购买
            </div>
            <!-- 不可购买 显示立即开通 -->
            <div
              class="login-btn"
              v-else-if="!isVip && courseData.accessMode === 4"
            >
              开通会员
            </div>
          </template>
          <template v-else>
            <div class="login-btn" @click="isApp = true">参与学习</div>
          </template>
        </div>
      </div>
    </transition>
  </div>
  <div class="mask" v-if="isApp">
    <div class="modal">
      <div class="moadl-tl">提示</div>
      <div class="modal-tx">请前往APP学习</div>
      <div class="modal-btn" @click="linkCourse">知道了</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      courseData: {},
      isVip: false,
      searchParams: {},
      loginState: false,
      isVip: false,
      isApp: false,
      time: "",
      isUserInfoComplete: false,
      countdowm: {
        day: "00",
        hour: "00",
        minute: "00",
        second: "00",
      },
      timer: null,
    };
  },
  components: {},
  created() {
    this.isVip = JSON.parse(localStorage.getItem("isVip"));
    this.time = localStorage.getItem("vipTime")?.replaceAll("/", "-");
  },
  mounted() {
    var query = this.$route.query;
    this.searchParams.courseId = query.id ? query.id : "";
    this.init();
    this.loadData(); // 加载数据/course/detail
    this.getUserInfor();
    this.btnType();
    this.getUserCompleteInfo();
  },
  methods: {
    getCountdown(t) {
      let time = t ? Number(t) / 1000 : 0;
      var d = "00";
      var h = "00";
      var m = "00";
      var s = "00";
      if (t <= 0) {
        clearInterval(this.timer);
        this.countdowm = {
          day: "00",
          hour: "00",
          minute: "00",
          second: "00",
        };
        return;
      }
      if (time != 0) {
        let day = Math.floor(time / (60 * 60 * 24));
        let hour = Math.floor((time / (60 * 60)) % 24);
        let minute = Math.floor((time / 60) % 60);
        let second = Math.floor(time % 60);
        //`${day < 10 ? ('0' + day) : day}天${hour < 10 ? ('0' + hour) : hour}时${minute < 10 ? ('0' + minute) : minute}分${second < 10 ? ('0' + second) : second}秒`
        d = day < 10 ? "0" + day : day;
        h = hour < 10 ? "0" + hour : hour;
        m = minute < 10 ? "0" + minute : minute;
        s = second < 10 ? "0" + second : second;
      }
      this.countdowm = {
        day: d,
        hour: h,
        minute: m,
        second: s,
      };
      this.courseData.campaignCountdown =
        this.courseData.campaignCountdown - 1000;
    },
    getUserCompleteInfo() {
      this.$http
        .getUserCompleteInfo()
        .then(async (res) => {
          if (res.flag === 0) {
            this.isUserInfoComplete = res.data == 0 ? false : true;
          }
        })
        .catch((err) => {
          // this.$Message.error(err.response.data.message);
        });
    },
    gotoInforPage() {
      const actionType = this.$route.query.actionType;
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const type = this.$route.query.type ? this.$route.query.type : "";
      const info = {
        actionType: actionType,
        invitationCode: code,
        type: type,
        idx: 5,
      };
      localStorage.setItem("userInfo", JSON.stringify(info));
      this.$router.push({
        path: "/myinformation",
        query: {
          actionType: actionType,
          invitationCode: code,
          type: type,
        },
      });
    },
    gotoPay() {
      const actionType = this.$route.query.actionType;
      const code = this.$route.query.invitationCode
        ? this.$route.query.invitationCode
        : "";
      const type = this.$route.query.type ? this.$route.query.type : "";
      this.$router.push({
        path: "/vip",
        query: {
          actionType: 4,
          invitationCode: code,
        },
      });
    },
    payCrouse(specificationId) {
      if (this.courseData.accessMode == 1) {
        this.$router.push({
          path: "/login",
        });
      } else {
        const courseId = this.$route.query.id;
        const code = this.$route.query.invitationCode
          ? this.$route.query.invitationCode
          : "";
        const actionType = this.$route.query.actionType;
        const type = this.$route.query.type ? this.$route.query.type : "";
        this.$router.push({
          path: "/library/pay",
          query: {
            courseId: courseId,
            specificationId: specificationId,
            showType: 2,
            invitationCode: code,
            actionType: actionType,
            type: type,
          },
        });
      }
    },
    btnType() {
      const token = localStorage.getItem("access_token");
      if (token && token != null && token != "null") {
        this.loginState = true;
      }
    },
    loadData() {
      this.$http
        .getAnatomyMgCommodityDetailId(this.searchParams.courseId)
        .then((res) => {
          if (res.flag == 0) {
            this.courseData = res.data || {};
            this.searchParams.courseType = res.data.courseType;
            this.isCollect = res.data.collected;
            this.timer = setInterval(() => {
              this.getCountdown(this.courseData.campaignCountdown);
            }, 1000);
            // this.getRecommendList(); // 获取推荐列表
            this.getLibraryList();
          }
        })
        .catch((err) => {
          //   ElMessage.error();
        });
    },
    getUserInfor() {
      const userInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.userInfo = userInfo || {};
      if (!userInfo) return;
      this.$http
        .getUserHalo()
        .then((res) => {
          if (res.flag == 0) {
            for (var i = 0; i < res.data.length; i++) {
              if (res.data[i].code == 1) {
                const newTime = new Date().getTime();
                if (newTime <= res.data[i].expiration) {
                  this.isVip = true;
                }
              }
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    isCover(url) {
      let path = "";
      if (!url) {
        return path;
      }
      if (url.indexOf("https://") != -1) {
        path = url;
      } else {
        path = "https://i.zmylschool.com" + url;
      }
      return path;
    },
    init() {
      const s = document.createElement("script");
      s.type = "text/javascript";
      s.src = "//web.cdn.openinstall.io/openinstall.js";
      s.addEventListener(
        "load",
        () => {
          var data = OpenInstall.parseUrlParams();
          new OpenInstall(
            {
              appKey: "zpyiil", //appkey参数配置,需要自行替换对应的appkey
              onready: function () {
                var m = this;
                /*在app已安装的情况尝试拉起app*/
                m.schemeWakeup({
                  data: data,
                  channelCode: "test-channelcode",
                });
                window.wakeupOrInstall = function () {
                  this.rnum = this.rnum + 1;
                  m.wakeupOrInstall({
                    data: data,
                    channelCode: "test-channelcode",
                  });
                };
              },
            },
            data
          );
        },
        false
      );
      document.head.appendChild(s);
    },
    openCourse() {
      // console.log(1212)
      // alert('打开课程')
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
    linkCourse() {
      // alert('下载课程')
      // console.log(1212)
      window.wakeupOrInstall(); //此方法为scheme、Universal Link唤醒以及引导下载的作用（必须调用且不可额外自行跳转下载）
      return false;
    },
  },
};
</script>

<style lang='scss' scoped>
.user-title {
  font-size: 0.28rem !important;
}
.user-accessMode {
  padding: 0.02rem 0.04rem;
  background: linear-gradient(288deg, #fd551d 0%, #ffa789 100%);
  border-radius: 0.1rem 0.2rem 0.1rem 0.1rem;
  color: #ffffff;
  line-height: 0.14rem;
  font-size: 0.2rem;
  text-align: center;
  margin-right: 0.1rem;
}
</style>
